package com.sunseen.capacitormachine.modules.parameter.productparameter.edit;

import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.widget.Toast;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.selected.BaseSelectFormat;
import com.bin.david.form.data.table.FormTableData;
import com.bin.david.form.data.table.TableData;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.Form;
import com.sunseen.capacitormachine.databinding.FragmentEditSortingParameterBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.SetParameterEvent;

import androidx.databinding.ViewDataBinding;

import org.greenrobot.eventbus.EventBus;

/**
 * @author zest
 */
public class EditSortingParameterFragment extends BaseFragment {

    @Override
    protected int setLayout() {
        return R.layout.fragment_edit_sorting_parameter;
    }

    private Form selectForm;
    private int curCol = -1;
    private int curRow = -1;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        final FragmentEditSortingParameterBinding binding = (FragmentEditSortingParameterBinding) viewDataBinding;
        table = binding.table;
        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowYSequence(false);
        table.getConfig().setShowTableTitle(false);
        table.getConfig().getContentGridStyle()
                .setColor(getResources().getColor(R.color.table_content_grid_color));
        table.getConfig().getContentStyle()
                .setTextColor(getResources().getColor(R.color.table_content_text_color));
        table.setSelectFormat(new BaseSelectFormat());
        Form[][] form = new Form[][]{
                {
                        new Form(getString(R.string.short_circuit_voltage)),
                        new Form(getString(R.string.volt), 7),
                        new Form(getString(R.string.open_circuit_voltage)),
                        new Form(getString(R.string.volt), 7)
                },
                {
                        new Form(getString(R.string.leak_current_up_limit)),
                        new Form(getString(R.string.ua), 7),
                        new Form(getString(R.string.leak_current_middle_limit)),
                        new Form(getString(R.string.ua), 7)
                },
                {
                        new Form(getString(R.string.leak_current_low_limit)),
                        new Form(getString(R.string.ua), 7),
                        new Form(getString(R.string.un_age_voltage)),
                        new Form(getString(R.string.volt), 7)
                },
                {
                        new Form(getString(R.string.loss_angle_up_limit)),
                        new Form(getString(R.string.percent), 7),
                        new Form(getString(R.string.impedance_up_limit)),
                        new Form(getString(R.string.mo), 7)
                },
                {
                        new Form(getString(R.string.temperature_up_limit)),
                        new Form(getString(R.string.temp_unit_flag), 7),
                        new Form(getString(R.string.surge_up_limit)),
                        new Form(getString(R.string.volt), 7)
                },
                {
                        new Form(getString(R.string.capacitor_nominal)),
                        new Form(getString(R.string.uf), 7),
                        new Form(""),
                        new Form("", 7)
                },
                {
                        new Form(getString(R.string.excellent_product_up_limit)),
                        new Form(getString(R.string.uf), 7),
                        new Form(getString(R.string.excellent_product_low_limit)),
                        new Form(getString(R.string.uf), 7)
                },
                {
                        new Form(getString(R.string.good_product_up_limit)),
                        new Form(getString(R.string.uf), 7),
                        new Form(getString(R.string.good_product_low_limit)),
                        new Form(getString(R.string.uf), 7)
                },
                {
                        new Form(getString(R.string.good_product_2_up_limit)),
                        new Form(getString(R.string.uf), 7),
                        new Form(getString(R.string.good_product_2_low_limit)),
                        new Form(getString(R.string.uf), 7)
                }

        };
        FormTableData<Form> formTableData = FormTableData
                .create(table, "", 16, form);
        formTableData.setFormat((itemForm) -> {
            if (itemForm != null) {
                return itemForm.getContent();
            } else {
                return "";
            }
        });

        formTableData.setOnItemClickListener(new TableData.OnItemClickListener<Form>() {
            @Override
            public void onClick(Column column, String value, Form form, int col, int row) {
                selectForm = form;
                if (col % 8 == 0) {
                    binding.btnInput.setEnabled(false);
                    curCol = -1;
                    curRow = -1;
                } else {
                    binding.editInput.setText("");
                    binding.btnInput.setEnabled(true);
                    curCol = col;
                    curRow = row;
                    binding.editInput.setKeyListener(new DigitsKeyListener(false, true));
                }
            }
        });
        table.setTableData(formTableData);
        binding.editInput.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains(".")) {
                    int pointIndex = str.indexOf(".");
                    if (str.length() - pointIndex > 2) {
                        binding.editInput.setText(str.substring(0, pointIndex + 2));
                    }
                }
            }
        });
        binding.btnInput.setOnClickListener((v) -> {
            if (selectForm != null) {
                String content = binding.editInput.getText().toString();
                //用户未输入，或只输入了一个小数点，不做处理，提示用户输入错误
                if (content.length() == 0 || (content.length() == 1 && ".".equals(content))) {
                    Toast.makeText(_mActivity, getString(R.string.number_input_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (curCol == 1) {
                    switch (curRow) {
                        case 0: {
                            updateForm(content, getString(R.string.volt));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "shortCircuitV", value));
                        }
                        break;
                        case 1: {
                            updateForm(content, getString(R.string.ua));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "leakageUpperLimit", value));
                        }
                        break;
                        case 2: {
                            updateForm(content, getString(R.string.ua));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "leakageLowerLimit", value));
                        }
                        break;
                        case 3: {
                            updateForm(content, getString(R.string.percent));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "lossAngelUpperLimit", value));
                        }
                        break;
                        case 4: {
                            updateForm(content, getString(R.string.temp_unit_flag));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "upperTemperatureLimit", value));
                        }
                        break;
                        case 5: {
                            int value = (int) (Float.valueOf(content) * 10);
                            if (capacityValid(value)) {
                                updateForm(content, getString(R.string.uf));
                                EventBus.getDefault().post(new SetParameterEvent(true, "capacitorNominal", value));
                            }
                        }
                        break;
                        case 6: {
                            int value = (int) (Float.valueOf(content) * 10);
                            if (capacityValid(value)) {
                                updateForm(content, getString(R.string.uf));
                                EventBus.getDefault().post(new SetParameterEvent(true, "premiumLimit", value));
                            }
                        }
                        break;
                        case 7: {
                            int value = (int) (Float.valueOf(content) * 10);
                            if (capacityValid(value)) {
                                updateForm(content, getString(R.string.uf));
                                EventBus.getDefault().post(new SetParameterEvent(true, "goodProductUpperLimit", value));
                            }
                        }
                        break;
                        case 8: {
                            int value = (int) (Float.valueOf(content) * 10);
                            if (capacityValid(value)) {
                                updateForm(content, getString(R.string.uf));
                                EventBus.getDefault().post(new SetParameterEvent(true, "goodProduct2UpperLimit", value));
                            }
                        }
                        break;
                    }
                } else if (curCol == 9) {
                    switch (curRow) {
                        case 0: {
                            updateForm(content, getString(R.string.volt));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "openCircuitV", value));

                        }
                        break;
                        case 1: {
                            updateForm(content, getString(R.string.ua));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "leakageMiddleLimit", value));
                        }
                        break;
                        case 2: {
                            updateForm(content, getString(R.string.volt));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "unAgedVoltage", value));
                        }
                        break;
                        case 3: {
                            updateForm(content, getString(R.string.mo));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "upperImpedanceLimit", value));
                        }
                        break;
                        case 4: {
                            updateForm(content, getString(R.string.volt));
                            int value = (int) (Float.valueOf(content) * 10);
                            EventBus.getDefault().post(new SetParameterEvent(true, "surgeUpperLimit", value));
                        }
                        break;
                        case 5: {
                        }
                        break;
                        case 6: {
                            int value = (int) (Float.valueOf(content) * 10);
                            if (capacityValid(value)) {
                                updateForm(content, getString(R.string.uf));
                                EventBus.getDefault().post(new SetParameterEvent(true, "superiorLowerLimit", value));
                            }
                        }
                        break;
                        case 7: {
                            int value = (int) (Float.valueOf(content) * 10);
                            if (capacityValid(value)) {
                                updateForm(content, getString(R.string.uf));
                                EventBus.getDefault().post(new SetParameterEvent(true, "goodProductLowerLimit", value));

                            }
                        }
                        break;
                        case 8: {
                            int value = (int) (Float.valueOf(content) * 10);
                            if (capacityValid(value)) {
                                updateForm(content, getString(R.string.uf));
                                EventBus.getDefault().post(new SetParameterEvent(true, "goodProduct2LowerLimit", value));
                            }
                        }
                        break;
                    }
                }
            }
        });
    }

    private SmartTable table;

    private void updateForm(String content, String unit) {
        selectForm.setContent(content + unit);
        table.invalidate();
    }

    private boolean capacityValid(float value) {
        boolean flag = value >= 0 && value < 10000;
        if (!flag) {
            Toast.makeText(_mActivity, getString(R.string.capacity_range_tip), Toast.LENGTH_SHORT).show();
        }
        return flag;
    }
}

